package com.vcc.web.core.component;

import com.vcc.data.entity.CardType;
import com.vcc.web.core.config.AccountConfig;
import com.vcc.web.core.thread.PingPongReserveThread;
import com.vcc.service.service.CardTypeService;
import com.vcc.service.service.ReserveCardService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class ReserveCardComponent {


    private static final Logger logger = LoggerFactory.getLogger(ReserveCardComponent.class);

//    @Autowired
//    private PingPongComponent pingPongComponent;
    @Autowired
    private RedisComponent redisComponent;
    @Autowired
    private CardTypeService cardService;
    @Autowired
    private ReserveCardService reserveCardService;
    @Autowired
    private AccountConfig accountConfig;

//    @Scheduled(cron = "0 0/10 * * * ?")
//    public void heartbeat() {
//        logger.info("储备卡机制");
//        //本地不做储备
//        if ("dev".equals(accountConfig.getActive())) {
//            return;
//        }
//        //过滤掉为空和为0的卡种
//        List<Card> cardList = cardService.list()
//                .stream()
//                .filter(it -> it.getReserveCount() != null && it.getReserveCount() > 0)
//                .toList();
//        if (cardList.isEmpty()) {
//            return;
//        }
//        for (Card card : cardList) {
//            //已经储备数
//            //0 待使用  1 使用中  2 待回调
//            Long count1 = reserveCardService.countByCardIdAndStatus(card.getId(), 0);
//            Long count2 = reserveCardService.countByCardIdAndStatus(card.getId(), 2);
//            Integer count = Math.toIntExact(count1 + count2);
//            //如果储备数小于目标储备数
//            if (count < card.getReserveCount()) {
//                //以储备数和目标书的差距
//                long tempCount = card.getReserveCount() - count;
//                logger.info("储备线程开始,储备目标数{},待使用中数{},待回调中数{},差距量{}", card.getReserveCount(), count1, count2, tempCount);
//                if (tempCount < 100) {
//                    new PingPongReserveThread(pingPongComponent, reserveCardService, redisComponent, card.getId(), card.getCode(), Math.toIntExact(tempCount)).start();
//                } else {
//                    new PingPongReserveThread(pingPongComponent, reserveCardService, redisComponent, card.getId(), card.getCode(), 100).start();
//                }
//            }
//        }
//    }
}
